package org.example.test02.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class AliStreamChatUtil {



    private static final String API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
    private static final String API_KEY = "sk-5bffade0f3fb46d49abf169956ca460e"; // 替换为你的 API Key

    public static void StreamChat(){
        String requestBody = """
            {
                "model": "qwen-plus",
                "messages": [
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "你是谁？"}
                ],
                "stream": true
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        ObjectMapper mapper = new ObjectMapper();
        // 流式接收响应
        client.sendAsync(request, HttpResponse.BodyHandlers.ofLines())
                .thenAccept(response -> {
                    response.body().forEach(line -> {
                        if (line.startsWith("data:")) {
                            String json = line.substring(5).trim();
                            JsonNode root = null;
                            try {
                                root = mapper.readTree(json);
                            } catch (JsonProcessingException e) {
                                throw new RuntimeException(e);
                            }
                            String content = root
                                    .path("choices")
                                    .get(0)
                                    .path("delta")
                                    .path("content")
                                    .asText();
                            if (!json.equals("[DONE]")) {
                                System.out.println("Received: " + content); // 处理每块数据
                            }
                        }
                    });
                })
                .join();

    }




}
